package org.xserver.common.util;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.xserver.component.core.websocket.WSMessage;
import org.xserver.component.core.websocket.WebSocketClient;
import org.xserver.component.json.JsonManager;
import org.xserver.component.redis.util.RedisConstant;

import com.business.bean.DefaultJsonResponse;
import com.fasterxml.jackson.core.JsonProcessingException;

/**
 * 
 * @author Idol
 *
 */
public class MessageUtils {


    public static String getHttpGetUri(String uri){
        int index = -1;
        if (uri != null && uri.length() > 0 && ((index = uri.indexOf("?")) > - 1)) {
            String requestUri = uri.substring(0 , index );
            return requestUri;
        }
        return uri;
    }

    public static Map<String , Object> getHttpGetParams(String uri){
        int index = -1;
        if (uri != null && uri.length() > 0 && ((index = uri.indexOf("?")) > - 1)) {
            String requestUri = uri.substring(index + 1);
            String[] reqs = requestUri.split("&");
            if (reqs != null && reqs.length > 0) {
                Map<String , Object> params = new HashMap<>();
                //name value 交替
                for (String req : reqs) {
                    String[] nameAndValue = req.split("=");
                    if (nameAndValue != null && nameAndValue.length == 2) {
                        String name = nameAndValue[0];
                        String value = nameAndValue[1];
                        params.put(name , value);
                    }
                }
                return params;
            }
        }
        return null;
    }


    /**
     * 判断是否含有特殊字符
     *
     * @param str
     * @return true为包含，false为不包含
     */
    public static boolean isSpecialChar(String str) {
        String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
    }

    public static void sendMessage(Collection<WebSocketClient> clients , String message){
        if (clients != null) {
            for (WebSocketClient client : clients) {
                ChannelHandlerContext channelHandlerContext = client.getChannelHandlerContext();
                TextWebSocketFrame textFrame = new TextWebSocketFrame(message);
                channelHandlerContext.getChannel().write(textFrame);
            }
        }
    }



    public static String swapMessage( WSMessage message) throws JsonProcessingException{
        String msg = null;
        if (message != null) {
            message.newId();
            msg = JsonManager.json(message);
        }
        return msg;
    }



    public static void sendMessage(WebSocketClient client , WSMessage message) throws JsonProcessingException{
        ChannelHandlerContext channelHandlerContext = client.getChannelHandlerContext();
        TextWebSocketFrame textFrame = new TextWebSocketFrame(JsonManager.json(message));
        channelHandlerContext.getChannel().write(textFrame);
    }

    public static void sendMessage(WebSocketClient client , String message){
        ChannelHandlerContext channelHandlerContext = client.getChannelHandlerContext();
        TextWebSocketFrame textFrame = new TextWebSocketFrame(message);
        channelHandlerContext.getChannel().write(textFrame);
    }


    public static void sendPingMessage(WebSocketClient client){
        ChannelHandlerContext channelHandlerContext = client.getChannelHandlerContext();
        if (channelHandlerContext.getChannel().isWritable()) {
            PingWebSocketFrame ping = new PingWebSocketFrame();
            channelHandlerContext.getChannel().write(ping);
        }
    }




    public static WSMessage parseText(String textFrame){
        WSMessage message = null;
        message = JsonManager.getBean(textFrame , WSMessage.class);
        return message;
    }

	public static void sendTokenErrorMessage(WebSocketClient client) {
		DefaultJsonResponse<Object> response = new DefaultJsonResponse<Object>();
		
		try {
			response.setCode(RedisConstant.TOKEN_ERROE+"");
			response.setMsg(RedisConstant.TOKEN_ERROE_MSG);
			sendMessage(client,JsonManager.json(response));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
